/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tel.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tel.entity.Phone;
import com.jeeplus.modules.tel.service.PhoneService;

/**
 * 手机Controller
 * @author 手机
 * @version 2017-10-11
 */
@Controller
@RequestMapping(value = "${adminPath}/tel/phone")
public class PhoneController extends BaseController {

	@Autowired
	private PhoneService phoneService;
	
	@ModelAttribute
	public Phone get(@RequestParam(required=false) String id) {
		Phone entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = phoneService.get(id);
		}
		if (entity == null){
			entity = new Phone();
		}
		return entity;
	}
	
	/**
	 * 手机列表页面
	 */
	@RequiresPermissions("tel:phone:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tel/phoneList";
	}
	
		/**
	 * 手机列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tel:phone:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Phone phone, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Phone> page = phoneService.findPage(new Page<Phone>(request, response), phone); 
		return getBootstrapData(page);
	}
	
	
	/**
	 * 申请单填写
	 * @param phone
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "form")
	public String form(Phone phone, Model model) {
		
		String view = "Form";
		
		// 查看审批申请单
		if (StringUtils.isNotBlank(phone.getId())){//.getAct().getProcInsId())){

			// 环节编号
			String taskDefKey = phone.getAct().getTaskDefKey();
			
			// 查看工单
			if(phone.getAct().isFinishTask()){
				view = "View";
			}
			// 修改环节
			else if (taskDefKey.startsWith("modify")){
				view = "Form";
			}
			// 审核环节
			else if (taskDefKey.startsWith("audit")){
				view = "Audit";
			}
			
		}

		model.addAttribute("phone", phone);
		return "modules/tel/phone" + view;
	}
	
	/**
	 * 申请单保存/修改
	 * @param phone
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "save")
	public String save(Phone phone, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, phone)){
			return form(phone, model);
		}
		phoneService.save(phone);
		addMessage(redirectAttributes, "提交审批'" + "" + "'成功");
		if(phone.getId()==null || phone.getId().equals("")){
			return "redirect:" + adminPath + "/act/task/process/";
		}else{
			return "redirect:" + adminPath + "/act/task/todo/";
		}
		
	}

	/**
	 * 工单执行（完成任务）
	 * @param phone
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(Phone phone, Model model) {
		if (StringUtils.isBlank(phone.getAct().getFlag())
				|| StringUtils.isBlank(phone.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(phone, model);
		}
		phoneService.auditSave(phone);
		return "redirect:" + adminPath + "/act/task";
	}

	
	/**
	 * 删除手机
	 */
	@ResponseBody
	@RequiresPermissions("tel:phone:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Phone phone, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		phoneService.delete(phone);
		j.setMsg("删除手机成功");
		return j;
	}
	
	/**
	 * 批量删除手机
	 */
	@ResponseBody
	@RequiresPermissions("tel:phone:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			phoneService.delete(phoneService.get(id));
		}
		j.setMsg("删除手机成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tel:phone:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Phone phone, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "手机"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Phone> page = phoneService.findPage(new Page<Phone>(request, response, -1), phone);
    		new ExportExcel("手机", Phone.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出手机记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tel:phone:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Phone> list = ei.getDataList(Phone.class);
			for (Phone phone : list){
				try{
					phoneService.save(phone);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条手机记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条手机记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入手机失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tel/phone/?repage";
    }
	
	/**
	 * 下载导入手机数据模板
	 */
	@RequiresPermissions("tel:phone:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "手机数据导入模板.xlsx";
    		List<Phone> list = Lists.newArrayList(); 
    		new ExportExcel("手机数据", Phone.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tel/phone/?repage";
    }

}